package com.lbank.spiderflow.core.driver;

import com.lbank.spiderflow.model.SpiderNode;
import org.apache.commons.lang3.StringUtils;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Arrays;
import java.util.Collections;

@Component
public class ChromeDriverProvider implements DriverProvider {

    @Value("${selenium.driver.chrome:/usr/local/bin/chromedriver}")
    private String chromeDriverPath;

    @Override
    public String support() {
        return "chrome";
    }

    @Override
    public WebDriver getWebDriver(SpiderNode node, String proxyStr) throws IOException {

        System.setProperty("webdriver.chrome.driver", chromeDriverPath);

        System.setProperty("webdriver.chrome.verboseLogging", "true");
        ChromeOptions chromeOptions = new ChromeOptions();
        chromeOptions.addArguments("--verbose");  // Enable Chrome logging
        // 动态生成唯一的用户目录
        Path userDir = Files.createTempDirectory("chrome_profile_");
        chromeOptions.addArguments("--user-data-dir=" + userDir.toAbsolutePath());
        // 关键性能优化参数
        chromeOptions.addArguments(
                "--headless=new",
                "--disable-blink-features=AutomationControlled",
                "--no-sandbox",
                "--disable-dev-shm-usage",
                "--disable-gpu",
                "--disable-software-rasterizer",
                "--disable-extensions",
                "--disable-background-networking",
                "--disable-default-apps",
                "--disable-sync",
                "--disable-translate",
                "--disable-notifications",
                "--disable-logging",
                "--log-level=3",
                "--remote-debugging-port=0",  // 使用随机端口
                "--remote-allow-origins=*",
                "--disable-renderer-backgrounding",
                "--disable-backgrounding-occluded-windows",
                "--disable-background-timer-throttling",
                "--memory-pressure-off",
                "--enable-low-end-device-mode",
                "--force-color-profile=srgb"
        );


        // 在ChromeOptions中添加
        chromeOptions.addArguments("--single-process"); // 减少进程数
        chromeOptions.addArguments("--disk-cache-size=1"); // 禁用磁盘缓存
        chromeOptions.addArguments("--disable-application-cache");
        chromeOptions.addArguments("--disable-offline-load-stale-cache");
        chromeOptions.addArguments("--aggressive-cache-discard");

        // 设置内存限制
       // chromeOptions.addArguments("--renderer-process-limit=1");
       // chromeOptions.addArguments("--max-old-space-size=1024"); // 限制V8内存


        // 替换现有的反检测参数
        chromeOptions.setExperimentalOption("excludeSwitches",
                Arrays.asList("enable-automation", "enable-logging"));
        chromeOptions.setExperimentalOption("useAutomationExtension", false);

        // 添加新的指纹混淆参数
        chromeOptions.addArguments("--disable-web-security");
        chromeOptions.addArguments("--allow-running-insecure-content");
        chromeOptions.addArguments("--ignore-certificate-errors");
        chromeOptions.addArguments("--disable-webgl");
        chromeOptions.addArguments("--disable-popup-blocking");
        chromeOptions.addArguments(
                "--disable-blink-features=AutomationControlled",
                "--use-automation-extension=false",
                "--disable-infobars",
                "--disable-popup-blocking"
        );

        // 添加CDP命令绕过检测
        chromeOptions.addArguments("--disable-blink-features=AutomationControlled");
        chromeOptions.setExperimentalOption("excludeSwitches",
                Arrays.asList("enable-automation", "enable-logging"));

        // 基础参数
        chromeOptions.addArguments(
                "--disable-gpu",
                "--window-size=1920,1080",
                "--user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/123.0.6312.58 Safari/537.36",
                "--accept-lang=en-US,en;q=0.9"
        );

        // 反检测增强
        chromeOptions.setExperimentalOption("excludeSwitches", Collections.singletonList("enable-automation"));

        //设置其他参数
        String arguments = node.getStringJsonValue(ARGUMENTS);
        if(StringUtils.isNotBlank(arguments)){
            chromeOptions.addArguments(Arrays.asList(arguments.split("\r\n")));
        }
        ChromeDriver driver = new ChromeDriver(chromeOptions);

        // 反检测脚本：删除自动化特征
        driver.executeScript(
                "Object.defineProperty(navigator, 'webdriver', {get: () => undefined});" +
                        "Object.defineProperty(window, 'navigator', {value: {userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/123.0.6312.58 Safari/537.36', plugins: [], language: 'en-US'}, writable: false});" +
                        "window.chrome = {runtime: {}};"
        );
        return  driver;
    }
}
